package com.example.sfm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sfm.constant.JwtClaimsConstant;
import com.example.sfm.constant.MessageConstants;
import com.example.sfm.exception.ObjectException;
import com.example.sfm.handler.TemplateStyleHandler;
import com.example.sfm.mapper.TeachersMapper;
import com.example.sfm.mapper.UsersMapper;
import com.example.sfm.pojo.dto.*;
import com.example.sfm.pojo.entity.StudentRecords;
import com.example.sfm.pojo.entity.Teachers;
import com.example.sfm.pojo.entity.Users;
import com.example.sfm.pojo.vo.LoginVo;
import com.example.sfm.pojo.vo.UserExportVo;
import com.example.sfm.pojo.vo.UserVo;
import com.example.sfm.properties.JwtProperties;
import com.example.sfm.result.PageResult;
import com.example.sfm.service.IStudentRecordsService;
import com.example.sfm.service.IUsersService;
import com.example.sfm.utils.JwtUtil;
import com.example.sfm.utils.ThreadLocalUtil;
import com.example.sfm.utils.Util;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sfm
 * @since 2025-03-07
 */
@Service
@RequiredArgsConstructor
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
    @Lazy
    private final TeachersMapper teachersService;
    private final IStudentRecordsService recordsService;
    private final JwtProperties jwtProperties;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createUser(@NotNull UserCreateDto dto) {

        Users user = BeanUtil.copyProperties(dto, Users.class)
                .setPassword(Util.encryptPassword(dto.getPassword()));

        if (!save(user)) {
            throw new ObjectException("用户创建失败");
        }
        Integer role = dto.getRole();
        if (role.equals(1)) {
            teachersService.insert(new Teachers().setUserId(user.getId()).setTeacherName(dto.getFullName()).setTeacherNumber(dto.getStudentId()));
        } else if (role.equals(2)) {
            if (!recordsService.save(new StudentRecords().setUserId(user.getId()).setStudentNumber(dto.getStudentId()))) {
                throw new ObjectException("档案记录插入失败");
            }
        }

    }

    @Override
    public PageResult<UserVo> listUsers(@NotNull UserQueryDto dto) {
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<Users>()
                .like(StringUtils.isNotBlank(dto.getUsername()),
                        Users::getUsername, dto.getUsername())
                .like(StringUtils.isNotBlank(dto.getFullName()),
                        Users::getFullName, dto.getFullName())
                .eq(dto.getRole() != null, Users::getRole, dto.getRole())
                .orderByDesc(Users::getCreatedAt);

        Page<Users> page = page(new Page<>(dto.getPageNum(), dto.getPageSize()), wrapper);

        return new PageResult<>(page.getTotal(),
                page.getRecords().stream()
                        .map(this::convertToVo)
                        .toList());
    }

    private @NotNull UserVo convertToVo(Users user) {
        UserVo vo = BeanUtil.copyProperties(user, UserVo.class);
        vo.setRoleStr(convertRole(user.getRole()));
        return vo;
    }

    @Contract(pure = true)
    private String convertRole(@NotNull Integer role) {
        return switch (role) {
            case 0 -> "管理员";
            case 1 -> "教师";
            case 2 -> "学生";
            default -> "未知";
        };
    }

    @Override
    public void updateUser(Integer id, UserUpdateDto dto) {
        Users user = getById(id);
        if (user == null) throw new ObjectException("用户不存在");

        BeanUtil.copyProperties(dto, user, "password");
        if (!updateById(user)) {
            throw new ObjectException("更新失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUsers(@NotNull List<Integer> ids) {
        // 检查关联数据
        ids.forEach(id -> {
            if (teachersService.exists(new LambdaQueryWrapper<Teachers>().eq(Teachers::getUserId, id))) {
                throw new ObjectException("用户存在关联教师档案");
            }
            if (recordsService.exists(new LambdaQueryWrapper<StudentRecords>().eq(StudentRecords::getUserId, id))) {
                throw new ObjectException("用户存在关联学生档案");
            }
        });
        if (!removeBatchByIds(ids)) {
            throw new ObjectException("删除失败");
        }
    }

    @Override
    public void resetPassword(Integer id) {
        Users user = getById(id);
        user.setPassword(Util.encryptPassword(JwtClaimsConstant.INITIAL_PASSWORD));
        updateById(user);
    }

    @Override
    public UserVo finById(Integer userId) {
        Users user = getById(userId);
        if (user == null) {
            throw new ObjectException(MessageConstants.USER_NOT_FOUND);
        }
        return convertToVo(user);
    }

    @Override
    public void register(@NotNull RegisterDto dto) {

        Users user = BeanUtil.copyProperties(dto, Users.class)
                .setRole(2)
                .setPassword(Util.encryptPassword(dto.getPassword()));


        if (!save(user)) {
            throw new ObjectException("注册失败");
        }

        if (!recordsService.save(new StudentRecords().setUserId(user.getId()).setStudentNumber(dto.getStudentId()))) {
            throw new ObjectException("档案记录插入失败");
        }
    }

    @Override
    public LoginVo login(LoginDto loginDto) {
        Users user = getOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, loginDto.getUsername()));
        //用户不存在
        if (user == null) {
            throw new ObjectException("用户不存在，请检查用户名");
        }
        String password = DigestUtil.md5Hex(loginDto.getPassword().getBytes());
        //密码不正确
        if (!user.getPassword().equals(password)) {
            throw new ObjectException("账号或者密码错误，请检查");
        }
        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        update(user, new LambdaUpdateWrapper<Users>()
                .set(Users::getLastLoginTime, LocalDateTime.now())
                .eq(Users::getId, user.getId()));
        return new LoginVo(JwtUtil.createJwt(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims), user.getRole());
    }

    @Override
    public void changePassword(ChangePasswordDto changePasswordDto) {
        // 获取当前用户
        Integer userId = ThreadLocalUtil.getId();
        Users users = baseMapper.selectById(userId);
        if (users == null) {
            throw new ObjectException(MessageConstants.USER_NOT_FOUND);
        }
        // 校验旧密码
        String encryptedOldPassword = Util.encryptPassword(changePasswordDto.getOldPassword());
        if (!users.getPassword().equals(encryptedOldPassword)) {
            throw new ObjectException(MessageConstants.PASSWORD_ERR);
        }

        // 校验新旧密码是否一致
        String encryptedNewPassword = Util.encryptPassword(changePasswordDto.getNewPassword());
        if (users.getPassword().equals(encryptedNewPassword)) {
            throw new ObjectException(MessageConstants.PASSWORD_IDENTICAL);
        }

        // 更新密码
        int updated = baseMapper.update(new LambdaUpdateWrapper<Users>().set(Users::getPassword, encryptedNewPassword).eq(Users::getId, userId));

        if (updated <= 0) {
            throw new ObjectException(MessageConstants.PASSWORD_UPDATE_FAIL);
        }
    }

    @Override
    public void exportUsers(HttpServletResponse response, UserQueryDto dto) {
        try {
            List<UserExportVo> data = listUsers(dto).getItems().stream().map(users ->
                    BeanUtil.copyProperties(users, UserExportVo.class)).toList();

            if (CollectionUtil.isEmpty(data)) {
                throw new ObjectException("导出数据为空");
            }
            String fileName = URLEncoder.encode(String.valueOf(LocalDate.now()), StandardCharsets.UTF_8);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

            // 写入数据
            EasyExcel.write(response.getOutputStream(), UserExportVo.class)
                    .registerWriteHandler(new TemplateStyleHandler())
                    .sheet("用户信息")
                    .doWrite(data);

            // 手动刷新流
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new ObjectException("导出失败");
        }
    }

    @Override
    public void userUpdate(UserUpdateDto2 dto) {
        Users user = getById(ThreadLocalUtil.getId());
        if (user == null) throw new ObjectException("用户不存在");

        BeanUtil.copyProperties(dto, user, "password");
        if (!updateById(user)) {
            throw new ObjectException("更新失败");
        }
    }
}
